package controller

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"struggle/logic"
	"struggle/model"
)

// 参数校验 --> 校验必要的数据是否存在
// 防止 XSS 攻击 --> `html/template` 内容检测和转义
// 敏感词过滤 --> 涉黄、涉恐等屏蔽词
// 数据库创建记录 --> dao 层创建记录
func QuestionSubmitHandler(c *gin.Context) {
	var question = new(model.Question)
	err := c.BindJSON(question)
	if err != nil {
		ResponseError(c, CodeInvalidParams)
		return
	}

	if len(question.Caption) == 0 || len(question.Content) == 0 {
		ResponseError(c, CodeInvalidParams)
		return
	}

	userSn, err := getCurrentUserSn(c)
	if err != nil {
		zap.L().Error("用户提交问题时未登录")
		ResponseError(c, CodeNotLogin)
		return
	}
	question.AuthorID = userSn

	if err := logic.CreateQuestion(question); err != nil {
		zap.L().Error("create question failed", zap.Error(err))
		ResponseError(c, CodeServerBusy)
	}
	zap.L().Debug("create question success", zap.Any("question", question))
	ResponseSuccess(c, question.QuestionID)
}

// QuestionListHandler 问题列表 GET 请求
func QuestionListHandler(c *gin.Context) {
	offset, limit := getOffsetAndLimit(c)
	zap.L().Debug("get question list param success",
		zap.Int("offset", offset),
		zap.Int("limit", limit))

	data, err := logic.GetQuestionList(offset, limit)
	if err != nil {
		zap.L().Error("logic.GetQuestionList failed", zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	zap.L().Debug("get question list success", zap.Any("data", data))
	ResponseSuccess(c, data)
}

// QuestionDetailHandler 问题详情 GET 请求
func QuestionDetailHandler(c *gin.Context) {
	questionID, err := getIDFromQuery(c, "question_id")
	if err != nil {
		zap.L().Error("invalid query param", zap.Error(err))
		ResponseError(c, CodeInvalidParams)
		return
	}

	// 给指定的问题阅读数+1
	ip := c.ClientIP()
	err = logic.DefaultArticle.IncReadCount(questionID, ip, 1)
	if err != nil {
		zap.L().Error("IncReadCount failed", zap.Error(err))
		return
	}

	// 获取问题详情
	data, err := logic.GetQuestionDetail(questionID)
	if err != nil {
		zap.L().Error("get question detail failed", zap.Error(err))
	}

	// 获取问题的扩展表数据
	dataEx, err := logic.DefaultQuestion.FindEx(questionID)

	// 构造返回数据
	res := map[string]interface{}{
		"question": data,
		"ex":       dataEx,
	}
	zap.L().Debug("question detail", zap.Any("res", res))
	ResponseSuccess(c, res)
}
